package cn.sdut.socket.bio.tomcat;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 模拟Tomcat
 * Created by majiatao
 */
public class TomcatDemo extends Thread {
    Socket socket;

    public TomcatDemo(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            // 可以获取浏览器发送的信息
            InputStream inputStream = socket.getInputStream();
            byte[] inByte = new byte[1024];
            int length = inputStream.read(inByte);
            System.out.println("From Browser:" + new String(inByte, 0, length));// 结果见最后
            // 向浏览器发送数据
            OutputStream outputStream = socket.getOutputStream();
            String threadName = Thread.currentThread().getName();
            outputStream.write(("<html><head><title>demo</title></head>" +
                    "<body>Hello,Tomcat-" + threadName + "</body></html>").getBytes());
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(80); // 如果不是80，浏览器检查报错
        while (true) {
            Socket acceptSocket = serverSocket.accept();
            new TomcatDemo(acceptSocket).start();
        }
    }

    /** 以下是浏览器请求时的数据
     From Browser:GET /?aaa HTTP/1.1
     Host: localhost
     Connection: keep-alive
     Cache-Control: max-age=0
     Upgrade-Insecure-Requests: 1
     User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
     Sec-Fetch-User: ?1
     Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,;q=0.8,application/signed-exchange;v=b3
     Sec-Fetch-Site: none
     Sec-Fetch-Mode: navigate
     Accept-Encoding: gzip, deflate, br
     Accept-Language: zh-CN,zh;q=0.9
     */
}
